package com.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.config.exception.MyException;
import com.google.common.collect.Maps;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Map;

@Component
public class GetTokenData {
    //公共密钥
    public static String SECRET = "YouRuanKeJiBi";
    public Map<String, String> getTokenData(String token){
        DecodedJWT jwt = null;

        JWTVerifier verifier = null;
        try {
            verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        try{
            jwt = verifier.verify(token);
        }catch (MyException e){
            throw new MyException(-505, "token过期");
        }
        Map<String, Claim> claimMap = jwt.getClaims();
        Map<String, String> resultMap = Maps.newHashMap();
        claimMap.forEach((k,v) -> resultMap.put(k, v.asString()));
        System.out.println("re:"+resultMap);
        return resultMap;
    }
}
